package com.mocoop.plugin.ajax;

import com.mocoop.commom.MyConstants;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Message;

public class HttpTask extends AsyncTask<String, String, String> {
	private Context context;
	private HttpUtil httpHelper;
	private String method;
	private String authorization;
	private HttpListeners httpListeners;
	private MyHttpTaskCallBack myHttpTaskCallBack;
	private boolean emitAjax;
	/*
	 * private Context context; private boolean interact = false;
	 */

	
    
	public void setHttpListeners(HttpListeners httpListeners) {
		this.httpListeners = httpListeners;
	}

	public void setEmitAjax(boolean emitAjax) {
		this.emitAjax = emitAjax;
	}

	public void setCallback(MyHttpTaskCallBack myHttpTaskCallBack) {
		this.myHttpTaskCallBack = myHttpTaskCallBack;
	}

	public void setAuthorization(String authorization) {
		this.authorization = authorization;
	}

	public HttpTask(Context context, String method) {
		super();

		this.context = context;
		this.method = method;
	}

	@Override
	protected String doInBackground(String... params) {
		String response = null;
		int timeOut = 30000;
		try{
		 timeOut = Integer.parseInt(params[2]);
		}catch(Exception e){
			timeOut = 30000;
		}
		httpHelper = new HttpUtil(timeOut);
		httpHelper.setAuthorization(authorization);
		
		
		if(httpListeners!=null){
			httpListeners.start();
		}
		
		try {

			if (params.length > 1) {
				if (method.toLowerCase().equals("post")) {
					
						response = httpHelper.postPage(params[0], params[1]);
					
				} else {
					response = httpHelper.getPage(params[0]);
				}

			} else {
				if (method.toLowerCase().equals("post")) {
					response = httpHelper.postPage(params[0], null);
				} else {
					response = httpHelper.getPage(params[0]);
				}
			}
			
			if(httpListeners!=null){
				httpListeners.end(response);
			}
			
			
		} catch (Exception e) {
			if(httpListeners!=null)
			httpListeners.myexception(e);
			response = "{\"myerror\":\""+e.getClass().getName()+"\"}";
			
		}
		return response;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if(myHttpTaskCallBack!=null){
			myHttpTaskCallBack.onSuccess(result);
		}
		
	}

	
	@Override
	protected void onProgressUpdate(String... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		if(httpListeners!=null){
			httpListeners.onProgressUpdate(values[0]);
		}
	}
	
	public interface HttpListeners {
		public void start();

		public void end(String response);

		public void myexception(Exception e);
		
		public void onProgressUpdate(String str);
	}
	
	public interface MyHttpTaskCallBack{
		public void onSuccess(String response);
	}
}
